package cn.didi.feidi.androidorder.fragment.personal;


import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.adapter.PersonMoneyDetailListViewAdapter;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.MoneyUserLog;

public class PersonBalanceDetailFragment extends FeidiBaseFragment {


    private static final String TAG = "PersonBalanceDetailFrag";
    private List<MoneyUserLog> moneyDetailItems = new ArrayList<MoneyUserLog>();
    private ListView balanceDetail_listView;
    private PersonMoneyDetailListViewAdapter personMoneyDetailListViewAdapter;

    private int pageSize = 8;
    private int pageNum = 1;

    private boolean isMore = true;

    private MoneyUserLog moneyUserLog = new MoneyUserLog();

    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static PersonBalanceDetailFragment newInstance(Bundle bundle) {
        PersonBalanceDetailFragment fragment = new PersonBalanceDetailFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_layout_person_money_detail, container, false);
        Log.d(TAG, "initFragment");
        return rootView;
    }

    @Override
    protected void initViews(View rootView) {
        balanceDetail_listView = (ListView) rootView.findViewById(R.id.person_money_detail_list_view);

        personMoneyDetailListViewAdapter = new PersonMoneyDetailListViewAdapter(getContext(), R.layout.item_person_wallet_balance_detail, moneyDetailItems);
        balanceDetail_listView.setAdapter(personMoneyDetailListViewAdapter);
    }

    @Override
    protected void initData() {
        //  : 2017/7/23 配置余额信息
        Map<String, String> params = new HashMap<>();

        params.put("userId", UserManager.getUserId());
        params.put("token", UserManager.getToken());
        params.put("pageNum", String.valueOf(pageNum));
        params.put("pageSize", String.valueOf(pageSize));

        executeRequest(new AppActionRequest<>(Api.GET_MONEY_USER_LOGS, params,
                new TypeToken<ApiResponse<List<MoneyUserLog>>>() {
                }.getType(), new ActionCallbackListener<List<MoneyUserLog>>() {
            @Override
            public void onSuccess(String message, List<MoneyUserLog> data) {
                moneyUserLog.setReason(0);
                moneyUserLog.setBalance(0.0);
                moneyUserLog.setBalanceChange(0.0);
                moneyUserLog.setCreateTime(0);

                if (data != null && !data.isEmpty()) {
                    if (data.size() == pageSize) {
                        moneyDetailItems.addAll(data);
                        moneyDetailItems.add(moneyUserLog);
                        personMoneyDetailListViewAdapter.notifyDataSetChanged();
                    } else {
                        moneyDetailItems.addAll(data);
                        moneyDetailItems.add(moneyUserLog);
                        personMoneyDetailListViewAdapter.setMore(false);
                        personMoneyDetailListViewAdapter.notifyDataSetChanged();
                    }
                } else {
                    isMore = false;
                    moneyDetailItems.add(moneyUserLog);
                    personMoneyDetailListViewAdapter.setMore(false);
                    personMoneyDetailListViewAdapter.notifyDataSetChanged();
                    Log.d(TAG, message);
                }
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);
                switch (errorEvent) {
                    case ErrorEvent.PARAM_NULL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ILLEGAL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ACCESS_FAILURE:
                        makeToast("网络异常，访问失败");
                        break;
                    default:
                        makeToast("未知错误");
                        break;
                }
            }
        }));
    }

    @Override
    protected void addListener() {
        balanceDetail_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == moneyDetailItems.size() - 1 && isMore) {
                    Map<String, String> params = new HashMap<>();
                    pageNum++;
                    personMoneyDetailListViewAdapter.setLoadText("正在加载");
                    personMoneyDetailListViewAdapter.notifyDataSetChanged();

                    params.put("userId", UserManager.getUserId());
                    params.put("token", UserManager.getToken());
                    params.put("pageNum", String.valueOf(pageNum));
                    params.put("pageSize", String.valueOf(pageSize));

                    executeRequest(new AppActionRequest<>(Api.GET_MONEY_USER_LOGS, params,
                            new TypeToken<ApiResponse<List<MoneyUserLog>>>() {
                            }.getType(), new ActionCallbackListener<List<MoneyUserLog>>() {
                        @Override
                        public void onSuccess(String message, List<MoneyUserLog> data) {
                            if (data != null && !data.isEmpty()) {
                                if (data.size() == pageSize) {
                                    moneyDetailItems.remove(moneyUserLog);
                                    moneyDetailItems.addAll(data);
                                    moneyDetailItems.add(moneyUserLog);
                                    personMoneyDetailListViewAdapter.setLoadText("加载更多");
                                    personMoneyDetailListViewAdapter.notifyDataSetChanged();
                                } else {
                                    isMore = false;
                                    moneyDetailItems.remove(moneyUserLog);
                                    moneyDetailItems.addAll(data);
                                    moneyDetailItems.add(moneyUserLog);
                                    personMoneyDetailListViewAdapter.setMore(false);
                                    personMoneyDetailListViewAdapter.setLoadText("没有更多数据了");
                                    personMoneyDetailListViewAdapter.notifyDataSetChanged();
                                }
                            } else {
                                isMore = false;
                                personMoneyDetailListViewAdapter.setMore(false);
                                personMoneyDetailListViewAdapter.setLoadText("没有更多数据了");
                                personMoneyDetailListViewAdapter.notifyDataSetChanged();
                                makeToast("没有更多数据了");
                                Log.d(TAG, message);
                            }
                        }

                        @Override
                        public void onFailure(int errorEvent, String message) {
                            Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);
                            switch (errorEvent) {
                                case ErrorEvent.PARAM_NULL:
                                    makeToast("参数为空");
                                    break;
                                case ErrorEvent.PARAM_ILLEGAL:
                                    makeToast("参数为空");
                                    break;
                                case ErrorEvent.PARAM_ACCESS_FAILURE:
                                    makeToast("网络异常，访问失败");
                                    break;
                                default:
                                    makeToast("未知错误");
                                    break;
                            }
                        }
                    }));
                }
            }
        });
        balanceDetail_listView.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                //有更多
                if (totalItemCount > visibleItemCount) {

                    //不满一屏
                } else {

                }
            }
        });
    }

}
